package com.zpark.it.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zpark.it.clients.ProductClient;
import com.zpark.it.mapper.CartMapper;
import com.zpark.it.param.CartSavaParam;
import com.zpark.it.param.ProductCollectParam;
import com.zpark.it.param.ProductIdParam;
import com.zpark.it.pojo.Cart;
import com.zpark.it.pojo.Product;
import com.zpark.it.service.CartService;
import com.zpark.it.utils.R;
import com.zpark.it.vo.CartVo;
import jdk.nashorn.internal.ir.annotations.Ignore;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.plugin2.applet.context.InitialJNLPExecutionContext;

import javax.jws.Oneway;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Title: CartServiceImpl 购物车添加数据实现类
 * @Author Charles
 * @Package com.zpark.it.service.impl
 * @Date 2023/7/26 11:24
 */

@Service
@Slf4j
public class CartServiceImpl implements CartService {


    @Autowired

    private CartMapper cartMapper;

    @Autowired
    private ProductClient productClient;

    /**
     * 购物车添加方法
     *
     * @param cartSavaParam
     * @return
     */
    @Override
    public R save(CartSavaParam cartSavaParam) {
        //1、查询商品数据
        ProductIdParam productIdParam = new ProductIdParam();
        productIdParam.setProductID(cartSavaParam.getProductId());
        Product product = productClient.productDetail(productIdParam);

        if (product == null) {
            return R.fail("商品已经被删除，无法添加到购物车");
        }

        //2、检查库存
        if (product.getProductNum() == 0) {
            R ok = R.ok("没有库存，无法购买");
            ok.setCode("003");
            log.info("业务结束：{}", ok);
            return ok;
        }
        //3、检查是否添加过
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", cartSavaParam.getUserId());
        queryWrapper.eq("product_id", cartSavaParam.getProductId());
        Cart cart = cartMapper.selectOne(queryWrapper);
        if (cart != null) {
            //证明购物车数据存在
            //在原有的基础上数量加一
            cart.setNum(cart.getNum() + 1);
            cartMapper.updateById(cart);
            //返回002提示即可
            R ok = R.ok("购物车存在该商品，数量+1");
            ok.setCode("002");
            log.info("业务结束：{}", ok);
            return ok;


        }
        //4、添加购物车
        cart = new Cart();
        cart.setNum(1);
        cart.setUserId(cartSavaParam.getUserId());
        cart.setProductId(cartSavaParam.getProductId());
        int rows = cartMapper.insert(cart);
        log.info("业务结束：{}", rows);
        //5、结果封装返回
        CartVo cartVo = new CartVo(product, cart);
        return R.ok("购物车数据添加成功", cartVo);
    }

    /**
     * 返回购物车数据
     *
     * @param userId
     * @return
     */
    @Override
    public R list(Integer userId) {
        //1、根据用户id， 查询购物车数据
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        List<Cart> carts = cartMapper.selectList(queryWrapper);


        //2、判断是否存在，不存在，返回空集合
        if (carts == null || carts.size() == 0) {
            carts = new ArrayList<>();//必须返回空数据
            return R.ok("购物车为空", carts);
        }

        //3、存在获取商品id集合，并且调用商品服务查询
        List<Integer> productIds = new ArrayList<>();
        for (Cart cart : carts) {
            productIds.add(cart.getProductId());

        }
        ProductCollectParam productCollectParam = new ProductCollectParam();
        productCollectParam.setProductIds(productIds);
        List<Product> productList = productClient.cartList(productCollectParam);
        //商品的集合转成商品map，商品的id为key。商品为value
        //jdk 1.8
        Map<Integer, Product> productMap = productList.stream().collect(Collectors.toMap(Product::getProductId, v -> v));
        //4、进行Vo的封装
        List<CartVo> cartVoList = new ArrayList<>();

        for (Cart cart : carts) {
            CartVo cartVo = new CartVo(productMap.get(cart.getProductId()), cart);
            cartVoList.add(cartVo);
        }
        R r = R.ok("数据库查询成功", cartVoList);
        return r;
    }

    /**
     * 跟新购物车数据
     *
     * @param cart
     * @return
     */
    @Override
    public R update(Cart cart) {
        //1、查询商品数据
        //2、判断库存是否可用
        //3、正常修改即可

        ProductIdParam productIdParam = new ProductIdParam();
        productIdParam.setProductID(cart.getProductId());
        Product product = productClient.productDetail(productIdParam);

        //判断库存
        if (cart.getNum() > product.getProductNum()) {
            return R.fail("修改失败，库存不足");
        }
        //修改数据库
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", cart.getUserId());
        queryWrapper.eq("product_id", cart.getProductId());
        Cart newCart = cartMapper.selectOne(queryWrapper);

        newCart.setNum(cart.getNum());
        int rows = cartMapper.updateById(newCart);
        log.info("业务结束：{}", rows);
        return R.ok("修改购物车数量成功");
    }

    /**
     * 删除购物车数据
     *
     * @param cart
     * @return
     */
    @Override
    public R remove(Cart cart) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", cart.getUserId());
        queryWrapper.eq("product_id", cart.getProductId());
        int rows = cartMapper.delete(queryWrapper);
        log.info("业务结束：{}", rows);
        return R.ok("删除购物车数据成功");

    }

    /**
     * 清空对应id的购物车
     *
     * @param cartIds
     */
    @Override
    public void clearIds(List<Integer> cartIds) {

        cartMapper.deleteBatchIds(cartIds);
        log.info("业务结束：{}",cartIds);

    }

    /**
     * 查询购物车
     *
     * @param productId
     * @return
     */
    @Override
    public R check(Integer productId) {

        QueryWrapper<Cart> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("product_id",productId);

        Long count = cartMapper.selectCount(queryWrapper);
        if (count>0) {
            return R.fail("有"+count+"件购物车引用,删除失败");
        }
        return R.ok("购物车无商品引用");
    }
}
